#include "misc.h"
#include "esp_system.h"
#include "esp_heap_caps.h"
#include "esp_chip_info.h"
#include "esp_timer.h"
#include "esp_netif.h"

/******************** 互斥锁管理 ********************/
static SemaphoreHandle_t print_mutex = NULL;

void misc_init() 
{
    if (!print_mutex) {
        print_mutex = xSemaphoreCreateMutex();
    }
}

/******************** 系统信息模块 ********************/
void misc_print_chip_info() 
{
    esp_chip_info_t chip;
    esp_chip_info(&chip);
    uint64_t uptime = esp_timer_get_time()/1000000;
    
    printf("\n\033[36m====== 系统状态监控 [运行:%llds] ======\033[0m\n", uptime);
    printf("芯片型号: %s Rev%d.%d 核心数:%d\n", 
           CONFIG_IDF_TARGET, chip.revision/100, chip.revision%100,
           chip.cores);
}

/******************** 内存监控模块 ********************/
#if CONFIG_MISC_ENABLE_MEM_STATS
void misc_print_mem_stats() 
{
    size_t internal_free = heap_caps_get_free_size(MALLOC_CAP_INTERNAL);
    size_t psram_free = heap_caps_get_free_size(MALLOC_CAP_SPIRAM);
    size_t min_heap = esp_get_minimum_free_heap_size();
    
    printf("\n\033[33m[内存状态]\033[0m\n");
    printf("内部RAM: %6.2fKB 可用 (历史最小:%.2fKB)\n", 
           internal_free/1024.0f, min_heap/1024.0f);
    printf("最大可用块:%.2fKB\n",
           heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL)/1024.0f);
           
    if (psram_free > 0) {
        printf("外部PSRAM:%6.2fKB 可用 | 最大块:%.2fKB\n",
               psram_free/1024.0f, 
               heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)/1024.0f);
    }
}
#endif

/******************** 任务监控模块 ********************/
#if CONFIG_MISC_ENABLE_TASK_STATS
void misc_print_task_stats(bool detail) 
{
    UBaseType_t task_count = uxTaskGetNumberOfTasks();
    printf("\n\033[33m[任务状态]\033[0m 总数:%d CPU使用率:%.1f%%\n", \
           task_count, 100.0f - (heap_caps_get_free_size(MALLOC_CAP_8BIT)*100.0f/esp_get_minimum_free_heap_size()));
    
    #if configUSE_TRACE_FACILITY
    TaskStatus_t *tasks = pvPortMalloc(task_count * sizeof(TaskStatus_t));
    if (tasks) {
        task_count = uxTaskGetSystemState(tasks, task_count, NULL);
        if (detail) {
            for (int i=0; i<task_count; i++) {
                printf(" %-16s Prio:%2d Stack:%lu\n", 
                       tasks[i].pcTaskName, 
                       tasks[i].uxCurrentPriority,
                       tasks[i].usStackHighWaterMark);
            }
        }
        vPortFree(tasks);
    }
    #endif
}
#endif

/******************** 主接口函数 ********************/
void misc_print_system_status(bool detail) 
{
    misc_init();
    xSemaphoreTake(print_mutex, portMAX_DELAY);
    
    misc_print_chip_info();
    
#if CONFIG_MISC_ENABLE_MEM_STATS
    misc_print_mem_stats();
#endif
    
#if CONFIG_MISC_ENABLE_TASK_STATS
    misc_print_task_stats(detail);
#endif
    
    printf("\033[36m==================================\033[0m\n");
    xSemaphoreGive(print_mutex);
}
